#pragma once

#include <iostream>
#include <string>
#include <vector>
#include "InetAddr.hpp"
#include "Log.hpp"


using namespace LogModule;
using namespace MutexModule;

class Route
{
private:
    bool IsExist(InetAddr& peer)
    {
        for(auto& user : _online_user)
        {
            if(user == peer) return true;
        }
        return false;
    }

    void Adduser(InetAddr& peer)
    {
        LOG(LogLevel::INFO) << "Add a new online user: " << peer.StringAddr();
        _online_user.push_back(peer);
    }

    bool DeleteUser(InetAddr& peer)
    {
        for(auto it = _online_user.begin(); it != _online_user.end(); it++)
        {
            if(*it == peer)
            {
                LOG(LogLevel::INFO) << "Delete a online user: " << peer.StringAddr();
                _online_user.erase(it);
                return true;
            }
        }
        return false;
    }


public:
    Route()
    {}
    ~Route()
    {}

    void MessageRoute(int sockfd, const std::string& msg, InetAddr& peer)
    {
        MutexModule::LockGuard guard(_mtx);
        if(!IsExist(peer)) Adduser(peer);

        std::string send_msg = peer.StringAddr() + " say: " + msg;

        for(auto& user : _online_user)
        {
            sendto(sockfd, send_msg.c_str(), send_msg.size(), 0, (const struct sockaddr*)&(user.NetAddr()), sizeof(user.NetAddr()));
        }

        if(msg == "QUIT")
        {
            LOG(LogLevel::INFO) << peer.StringAddr() << " online user exit";
            DeleteUser(peer);
        }
    }
private:
    std::vector<InetAddr> _online_user;
    MutexModule::Mutex _mtx;
};